/**
 * Created by admin on 2016/8/9.
 */
var assert = require('../assert');
// 获取订单列表
exports.getOrders = function (req, res) {
    // 获取请求参数
    var userId = req.query.userId;
    var page = req.query.page;
    var status = req.query.status;
    var limit = 10;
    // 判断userId是否为空
    if (!userId){
        res.send(assert.response_sms(400, '需要参数userId'));
        return
    }
    // 判断分页
    if (typeof page == 'undefined'){
        page = 0;
    }else {
        try {
            page = parseInt(page) - 1;
        }catch (error){
            page = 0;
        }
    }
    // 判断status
    if (typeof status != 'undefined'){
        try {
            status = parseInt(status);
        }catch (error){
            status = 0;
        }
    }
    // 实例化一个用户
    var User = Parse.Object.extend('User');
    var user = new User();
    user.id = userId;
    // 查询订单
    var query = new Parse.Query('OPOrder');
    query.equalTo('user', user);
    if (status){
        query.equalTo('status', status);
    }
    query.limit(limit);
    query.skip(page*limit);
    query.doesNotExist('store');
    query.descending('createdAt');
    query.include('orderProducts', 'orderProducts.product', 'expressCompany', 'groupOrder', 'groupProduct');
    query.find().then(function (results) {
        // 格式化返回的样式
        var response_content = [];
        for (var i=0; i<results.length; i++){
            var temp = assert.obj2dic(results[i],['totalPrice', 'username', 'payPrice', 'status']);
            temp['isGroup'] = true;
            // 判断是不是团购
            if (typeof results[i].get('groupOrder') == 'undefined' && typeof results[i].get('groupProduct') == 'undefined'){
                temp['isGroup'] = false;
            }
            // 判断团购的状态
            if (typeof results[i].get('groupOrder') != 'undefined'){
                temp['groupStatus'] = results[i].get('groupOrder').get('status');
                temp['groupId'] = results[i].get('groupOrder').id;
                temp['groupProductId'] = results[i].get('groupProduct').id;
            }
            if (typeof results[i].get('groupProduct') != 'undefined'){
                temp['groupProductId'] = results[i].get('groupProduct').id;
            }
            temp['orderProducts'] = [];
            temp['createdAt'] = results[i].get('createdAt').Format('yyyy-MM-dd');
            temp['totalCount'] = 0;
            temp['expressNO'] = results[i].get('expressNumber');
            if (typeof results[i].get('expressCompany') != 'undefined'){
                temp['expressCom'] = results[i].get('expressCompany').get('code');
                temp['expressName'] = results[i].get('expressCompany').get('name');
            }
            var temp_orderProduct = {};
            if (typeof results[i].get('groupProduct') != 'undefined'){
                temp_orderProduct = assert.obj2dic(results[i].get('orderProducts')[0],['count']);
                temp_orderProduct['product'] = {};
                temp_orderProduct['product'] = assert.obj2dic(results[i].get('orderProducts')[0].get('product'), ['title', 'images']);
                temp_orderProduct['product']['images'] = temp_orderProduct['product']['images'][0];
                temp_orderProduct['price'] = results[i].get('groupProduct').get('groupPrice');
                temp['orderProducts'].push(temp_orderProduct);
                temp['totalCount'] = 1;
            }else {
                for (var j=0; j<results[i].get('orderProducts').length; j++){
                    temp_orderProduct = assert.obj2dic(results[i].get('orderProducts')[j],['count', 'price']);
                    temp_orderProduct['product'] = assert.obj2dic(results[i].get('orderProducts')[j].get('product'), ['title', 'images']);
                    temp_orderProduct['product']['images'] = temp_orderProduct['product']['images'][0];
                    temp['orderProducts'].push(temp_orderProduct);
                    temp['totalCount'] += results[i].get('orderProducts')[j].get('count');
                }
            }
            response_content.push(temp);
        }
        res.json(assert.con2json(200, '获取订单成功', response_content));
    }, function (error) {
        res.json(assert.con2json(400, '获取订单失败' + error.message));
    });
};
// 获取单个订单的详情
exports.getOrder = function (req, res) {

    var orderId = req.params.orderId;
    if (!orderId){
        res.send(assert.response_sms(400, '需要参数orderId'));
        return;
    }
    var query = new Parse.Query('OPOrder');
    query.include('orderProducts.product', 'expressCompany', 'orderProducts.orderReturn', 'groupOrder', 'groupProduct', 'coupon.couponTemplate');
    query.get(orderId).then(function (result) {
        // 格式化返回的字段
        var temp_order = assert.obj2dic(result,['expressPrice', 'username', 'payPrice', 'address', 'username','privilegePrice', 'mobile', 'totalPrice', 'status', 'createdAt', 'expressNumber']);
        temp_order['orderProducts'] = [];
        temp_order['createdAt'] = result.get('createdAt').Format('yyyy-MM-dd');
        temp_order['totalCount'] = 0;
        temp_order['expressNO'] = result.get('expressNumber');
        // 判断是否是团购订单，添加团购相关信息
        temp_order['isGroup'] = false;
        if (typeof result.get('groupOrder') != 'undefined'){
            temp_order['isGroup'] = true;
            temp_order['groupStatus'] = result.get('groupOrder').get('status');
            temp_order['groupId'] = result.get('groupOrder').id;
            temp_order['groupProductId'] = result.get('groupProduct').id;

        }
        // 判断是否已经有快递信息
        if (typeof result.get('expressCompany') != 'undefined'){
            temp_order['expressCom'] = result.get('expressCompany').get('code');
            temp_order['expressName'] = result.get('expressCompany').get('name');
        }
        // 判断是否有优惠券的使用
        if (typeof result.get('coupon') != 'undefined'){
            temp_order['privilegePrice'] += result.get('coupon').get('couponTemplate').get('worth');
        }
        for (var i=0; i<result.get('orderProducts').length; i++){
            var temp_orderProduct = assert.obj2dic(result.get('orderProducts')[i],['count']);
            if (typeof result.get('groupProduct') != 'undefined'){
                temp_orderProduct['price'] = result.get('groupProduct').get('groupPrice');
            }else {
                temp_orderProduct['price'] = result.get('orderProducts')[i].get('price');
            }
            var message = result.get('orderProducts')[i].get("message");
            // 判断有无备注
            if (typeof message == 'undefined'){
                temp_orderProduct['message'] = '无备注';
            }else {
                temp_orderProduct['message'] = result.get('orderProducts')[i].get('message');
            }
            // 判断order是否有申请退货
            var orderReturnTag = result.get('orderProducts')[i].get('orderReturn');
            // 判断退货
            temp_orderProduct['orderReturn'] = typeof orderReturnTag != 'undefined';
            temp_orderProduct['product'] = assert.obj2dic(result.get('orderProducts')[i].get('product'), ['title', 'images']);
            temp_orderProduct['product']['images'] = temp_orderProduct['product']['images'][0];
            temp_order['orderProducts'].push(temp_orderProduct);
            temp_order['totalCount'] += result.get('orderProducts')[i].get('count');
        }
        // 用时间戳做订单号
        temp_order['orderId'] = Date.parse(result['createdAt']);
        res.json({'code': 200, 'message': '获取订单成功','results': temp_order});
    }, function (error) {
        res.send(assert.response_sms(400, '获取订单失败' + error.message));
    });
};
// 提交一个订单
exports.postOrder = function (req, res) {
    // 获取请求参数
    var userId = req.body.userId;
    var addressId = req.body.addressId;
    var memberId = req.body.memberId;// 店铺相关的 店长id，或者 店员Id
    var expressPrice = req.body.expressPrice;
    var totalPrice = req.body.totalPrice;
    var groupProductId = req.body.groupProductId;
    var groupId = req.body.groupOrderId;
    var couponId = req.body.couponId;
    var isCreateGroup = groupProductId != 'undefined' && groupId == 'undefined';
    var isJoinGroup = groupProductId != 'undefined' && groupId != 'undefined';
    var isGroup = isCreateGroup || isJoinGroup;
    try {
        var products = JSON.parse(req.body.products);
        expressPrice = parseInt(expressPrice);
    }catch (error){
        res.send(assert.response_sms(101, '商品信息获取错误', error));
        return
    }
    // 判断参数是否有空值，expressPrice可以为0.privilegePrice可以为0
    if (assert.check_parms([userId, addressId])){
        res.send(assert.response_sms(102, '用户ID和地址ID为空'));
        return;
    }
    var waitReq = [getAddress(addressId),getOrderProductInfo(products)];
    if(memberId){
        waitReq.push(getPharmacyInfo(memberId));
    }
    // 查找团购价格
    if (isGroup){
        waitReq.push(getGroupProductByGroupProductId(groupProductId));
    }
    if (typeof couponId != 'undefined'){
        waitReq.push(getCoupon(couponId));
    }
    Promise.all(waitReq).then(function (results) {
        var userAddress = results[0];
        //如果memberId存在,则获取店铺优惠信息
        if(memberId){
            var pharmacy = results[2];
            if(!pharmacy){
                memberId = '';
            }
        }
        if (memberId && isGroup){
            var groupPrice = results[3];
        }else if (!memberId && isGroup){
            var groupPrice = results[2];
        }
        if (typeof couponId != 'undefined'){
            var coupon = results.pop();
            if (coupon.get('order')){
                res.json({'code': 106, 'message': '此优惠券已经用过，不能再次使用'});
                return;
            }
        }
        //订单商品信息
        var orderProduct_list = results[1];
        //获取用户对象
        var User = Parse.Object.extend('User');
        var user = new User();
        user.id = userId;
        //计算总价
        var totalPrice = 0;
        for (var i=0; i<orderProduct_list.length; i++){
            totalPrice += orderProduct_list[i].get('price') * orderProduct_list[i].get('count');
        }
        totalPrice = totalPrice + expressPrice;
        if (isGroup){
            totalPrice = groupPrice;
        }
        var payPrice = undefined;
        if (typeof couponId != 'undefined'){
            if (coupon.get('couponTemplate').get('limitPrice')<totalPrice){
                payPrice = totalPrice - coupon.get('couponTemplate').get('worth');
            }else {
                res.json({'code': 105, 'message': '总价没有达到优惠券的限制额度'});
                return;
            }
        }else {
            payPrice = totalPrice;
        }
        //如果店铺优惠存在,则最终价格需要减去优惠价格
        if(memberId){
            payPrice = totalPrice - pharmacy.get('favorablePrice');
        }
        //生成订单
        var Order = Parse.Object.extend('OPOrder');
        var order = new Order();
        order.set('user', user);
        order.set('mobile', userAddress.get('tel'));
        order.set('status', 0);
        order.set('address', userAddress.get('address'));
        order.set('username', userAddress.get('name'));
        order.set('payPrice', payPrice);
        order.set('totalPrice', totalPrice);
        order.set('expressPrice', expressPrice);
        if (typeof couponId != 'undefined'){
            order.set('coupon', coupon);
        }
        if(memberId){
            order.set('privilegePrice', pharmacy.get('favorablePrice'));
            order.set('pharmacy', pharmacy);
            var saleUser = new User();
            saleUser.id = memberId;
            order.set('saleUser', saleUser);
        }else{
            order.set('privilegePrice', 0);
        }
        // 如果有团购标记，将这个团购插入到这个order里
        var GroupProduct = Parse.Object.extend('OPGroupProduct');
        var groupProduct = new GroupProduct();
        if (req.body.groupProductId != 'undefined' && req.body.groupOrderId == 'undefined'){
            // 创建一个团购
            groupProduct.id = groupProductId;
            order.set('groupProduct', groupProduct);
        }else if (req.body.groupOrderId != 'undefined' && req.body.groupProductId != 'undefined'){
            // 参加团购
            var GroupOrder = Parse.Object.extend('OPGroupOrder');
            var groupOrder = new GroupOrder();
            groupOrder.id = groupId;
            groupProduct.id = req.body.groupProductId;
            order.set('groupOrder', groupOrder);
            order.set('groupProduct', groupProduct);
        }
        if (req.body.city != 'undefined' && typeof req.body.city != 'undefined'){
            order.set('city', req.body.city);
        }
        order.set('orderProducts', orderProduct_list);
        order.save().then(function (result) {
            // 生成订单成功的回调
            var temp = assert.obj2dic(result,['totalPrice','payPrice', 'privilegePrice', 'address', 'expressPrice']);
            // 返回生成订单的数据
            res.send(assert.response_sms(200, '生成订单成功', temp));
            if (typeof couponId != 'undefined'){
                coupon.set('order', result);
                coupon.save().then(function (result) {
                    console.log('coupon绑定order成功');
                }, function (error) {
                    console.log('coupon绑定order失败', error.message);
                });
            }
            //删除购物车中得商品
            //TODO 如果是团购商品不需要执行删除购物车商品操作
            if (!isCreateGroup){
                deleteShoppingItem(products, user);
            }
        }, function (error) {
            // 生成订单失败的回调
            console.log('生成订单失败',error);
            res.send(assert.response_sms(103, '生成订单失败'));
        });
    }, function (err,error) {
        console.log('waitReq获取信息失败', error);
        res.send(assert.response_sms(500, '生成订单失败'));
    });
};
// 修改订单状态（取消订单,确认收货）
exports.editOrder = function (req, res) {
    var orderId = req.params.orderId;
    var status = req.body.orderStatus;
    try {
        status = parseInt(status);
    }catch (error){
        res.send(assert.response_sms(401, 'status参数错误'));
        return
    }
    if (!(orderId && status)){
        res.send(assert.response_sms(400, '参数不能为空'));
        return
    }
    var query = new Parse.Query('OPOrder');
    query.get(orderId).then(function (order) {
        order.set('status', status);
        return order.save()
    }, function (error) {
        res.send(assert.response_sms(400, '修改订单失败, 没有获取到相应的订单' + error.message));
    }).then(function (order) {
        res.send(assert.response_sms(200, '修改订单成功'));
        // 如果是确认收货，totalCost + 该订单货物的成本，unConfirmMoney - 该订单收益  activeMone y+ 利润  确认订单中
        if (status==3) {
            var cost = order.get('cost');
            var income = order.get('payPrice') - cost;
            var store = order.get('store');
            store.increment('totalCost', cost);
            store.increment('unConfirmMoney', -income);
            store.increment('activeMoney', income);
            store.save().then(function (result) {
                if (result.get("unConfirmMoney")<0){
                    result.set("unConfirmMoney", 0);
                    result.save().then(function (rets) {
                        console.log('修正js精度丢失');
                    });
                }
                console.log('store save success');
            }, function (error) {
                console.log('store save error');
            });
            // 插入一条消息，用作提示用户已经确认收货
            var StoreMessage = Parse.Object.extend('OPStoreMessage');
            var message = new StoreMessage();
            message.set('isRead', true);
            message.set('store', store);
            var title = '确认收货';
            var content = '您有订单确认收货';
            message.set('title', title);
            message.set('content', content);
            message.set('type', 'order');
            message.save().then(function (message) {
                console.log('message save success');
            }, function (error) {
                console.log('message save error');
            });
        }
    }, function (error) {
        res.send('401', '修改订单失败' + error.message);
    });
};
// 删除订单
exports.deleteOrder = function (req, res) {
    var orderId = req.params.orderId;
    if (!orderId){
        res.send(assert.response_sms(400, '参数不能为空'));
        return
    }
    var query = new Parse.Query('OPOrder');
    query.get(orderId).then(function (order) {
        var status = order.get('status');
        if (status==5||status==3){
        return order.destroy();
        }else {
            res.send(assert.response_sms(400, '此订单状态不能删除'));
        }
    }, function (error) {
        res.send(assert.response_sms(400, '删除订单失败, 没有找到对应订单' + error.message));
    }).then(function (result) {
        res.send(assert.response_sms(200, '删除订单成功', result));
    }, function (error) {
        res.send(assert.response_sms(400, '删除订单失败' + error.message));
    });
};
// 后台填写快递等信息
exports.setExpressInfo = function (req, res) {
    // 获取到订单id，快递单号，快递公司code
    var orderId = req.params.orderId;
    var expressNumber = req.body.expressNumber;
    var code = req.body.code;
    // 参数空值检查
    if (!(orderId && expressNumber && code)){
        res.send(assert.response_sms(400, '参数错误'));
        return
    }
    // 创建查询对象
    var queryOrder = new Parse.Query('OPOrder');
    var queryExpress = new Parse.Query('OPExpress');
    // 设置查询条件
    queryExpress.equalTo('code', code);
    //查询
    queryExpress.first().then(function (expressCompany) {
        if (expressCompany.length<1){
            res.send(assert.response_sms(400, '没有查询到相应的快递公司'));
            return
        }
        // 获取到对应的订单
        queryOrder.get(orderId).then(function (order) {
            order.set('expressNumber', expressNumber);
            order.set('expressCompany', expressCompany[0]);
            order.set('status', 2);
            return order.save();
        }, function (error) {
            res.send(assert.response_sms(400, '没有查询到相应的订单', error.message));
        }).then(function (result) {
            res.send(assert.response_sms(200, '添加订单信息成功', result));
        }, function (error) {
                res.send(assert.response_sms(400, '查询订单信息出错', error.message));
        });
    }, function (error) {
        res.send(assert.response_sms(400, '查询到相应的快递公司出错', error.message));
    });
};
// 付款成功回调函数
exports.setPayInfo = function (req, res, next) {
    var orderId = req.params.orderId;
    var payment = req.body.payment;
    var payOrderId = req.body.payOrderId;
    var hasNull = assert.check_parms([orderId,payment]);
    if (hasNull){
        res.send(assert.response_sms(400, '参数错误'));
        return
    }
    if (!(payment=='wx' || payment=='alipay')){
        res.send(assert.response_sms(400, '支付方式有误'));
        return
    }

    var query = new Parse.Query('OPOrder');
    query.get(orderId).then(function (order) {
        order.set('payment', payment);
        order.set('status', 1);
        order.set('payDate', new Date());
        order.set('payOrderId',payOrderId);
        order.set('payWay','web');
        return order.save();
    }, function (error) {
        res.send(assert.response_sms(400, '查询订单出错', error.message));
    }).then(function (result) {
        res.json(assert.con2json(200, '付款成功', result));
        // 支付成功后写入一条系统消息.setPayInfo  中
        var StoreMessage = Parse.Object.extend('OPStoreMessage');
        var message = new StoreMessage();
        var store = result.get('store');
        message.set('isRead', true);
        message.set('store', store);
        var title = '支付成功';
        var content = '您有新的订单支付成功';
        message.set('title', title);
        message.set('content', content);
        message.set('type', 'order');
        message.save().then(function (message) {
            console.log('message save success');
        }, function (error) {
            console.log('message save error');
        });
        // 修改store中的数据
        var income = result.get('payPrice') - result.get('cost');
        if (typeof store != 'undefined'){
            store.increment('unConfirmMoney', income);
            store.increment('totalMoney', income);
            store.save().then(function (store) {
                console.log('store modify success');
            }, function (error) {
                console.log('store modify error');
            });
        }
        // 判断order是开团订单还是参团订单
        var groupProduct = result.get('groupProduct');
        var groupOrder = result.get('groupOrder');
        if (typeof groupProduct != 'undefined' && typeof groupOrder == 'undefined'){
            // 开团
            req.userId = result.get('user').id;
            req.groupProductId = groupProduct.id;
            req.orderId = orderId;
            return next();
        }else if (typeof groupOrder != 'undefined' && typeof groupOrder != 'undefined'){
            // 参团
            req.userId = result.get('user').id;
            req.groupOrderId = groupOrder.id;
            req.orderId = orderId;
            return next();
        }
    }, function (error) {
        res.send(assert.response_sms(400, '付款失败', error.message));
    });
};
// 获取指定order内的所有商品
exports.getOrderProducts = function (req, res) {
    var orderId = req.query.orderId;
    if (!orderId){
        res.send(assert.response_sms(101, 'orderId为空值'));
        return
    }
    var query = new Parse.Query('OPOrder');
    query.include('orderProducts', 'orderProducts.product', 'orderProducts.comment');
    query.get(orderId).then(function (order) {
        var response_content = [];
        for (var i=0, len=order.get('orderProducts').length; i<len; i++){
            var temp = order.get('orderProducts')[i];
            var orderProduct = assert.obj2dic(temp, ['price', 'count']);
            orderProduct['product'] = assert.obj2dic(temp.get('product'),['title']);
            orderProduct['product']['image'] = temp.get('product').get('images')[0];
            var comment = temp.get('comment');
            if (comment){
                orderProduct['isComment'] = true;
            }else{
                orderProduct['isComment'] = false;
            }
            response_content.push(orderProduct);
        }
        res.send(assert.response_sms(200, '获取成功', response_content))
    }, function (error) {
       res.send(assert.response_sms(400, '获取失败'))
    });
};
// 获取每种订单的数量
exports.categoryOrderCount = function (req, res) {
    var userId = req.query.userId;
    Promise.all([getCategoryOrderCount(userId), getOrderReturnsCount(userId)]).then(function (results) {
        var normalOrders = results[0];
        var orderReturns = results[1];
        var response_content = {};
        response_content['waitPayNum'] = normalOrders[0];
        response_content['waitSendNum'] = normalOrders[1];
        response_content['waitAcceptNum'] = normalOrders[2];
        response_content['waitCommentNum'] = normalOrders[3];
        response_content['waitRefundNum'] = orderReturns;
        res.send(assert.response_sms(200, '获取成功', response_content));
    }, function (error) {
        res.send(assert.response_sms(400, '获取失败'))
    });
};
// 查询优惠码是否有效
exports.checkSaleCode = function (req, res) {
    var saleId = req.body.saleId;
    if (!saleId){
        res.send(assert.response_sms(101, '需要参数saleId'));
        return;
    }
    var User = Parse.Object.extend('User');
    var user = new User();
    user.id = saleId;
    // 查询优惠来至哪个店铺
    var ownerQuery = new Parse.Query('PYPharmacy');
    ownerQuery.equalTo('owner', user);
    var memberQuery = new Parse.Query('PYPharmacy');
    memberQuery.containedIn('members', [user]);
    var mainQuery = Parse.Query.or(ownerQuery, memberQuery);
    mainQuery.first().then(function (pharmacy) {
        // 判断是够查到店铺
        if (typeof (pharmacy) == 'undefined'){
            res.send(assert.response_sms(201, '验证失败,没有找到对应的店铺'));
            return;
        }
        var favor = pharmacy.get('favorablePrice');
        // 判断店铺是否存在优惠
        if (typeof (favor) != 'undefined'){
            res.send(assert.response_sms(200, '验证成功', {'salePrice': favor}));
        }else {
            res.send(assert.response_sms(202, '验证失败'));
        }
    }, function (error) {
        res.send(assert.response_sms(400, '验证失败'));
    });
};
// 提交一个用户反馈
exports.postFeedBack = function (req, res) {
    var userId = req.body.userId;
    var content = req.body.content;
    var contact = req.body.contact;
    var reg_phone = /^1[3|4|5|7|8]\d{9}$/;
    var reg_mail = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/;
    if (!reg_mail.test(contact) && !reg_phone.test(contact)){
        res.send(assert.response_sms(101, '联系方式格式错误'));
        return;
    }
    var hasNull = assert.check_parms(userId, content);
    if (hasNull){
        res.send(assert.response_sms(102, 'userId,content不能为空'));
        return;
    }
    var user = new Parse.User();
    user.id = userId;
    var FeedBack = new Parse.Object.extend('OPFeedBack');
    var feedback = new FeedBack();
    feedback.set('user', user);
    feedback.set('content', content);
    feedback.set('contact', contact);
    feedback.save().then(function (result) {
        res.send(assert.response_sms(200, '提交成功'))
    }, function (error) {
        res.send(assert.response_sms(400, '提交失败'))
    });
};
// 获取kdOrders
exports.getkdOrders = function (req, res) {
    // 获取请求参数
    var userId = req.query.userId;
    var page = req.query.page;
    var status = req.query.status;
    var limit = 10;
    // 判断userId是否为空
    if (!userId){
        res.send(assert.response_sms(400, '需要参数userId'));
        return
    }
    // 判断分页
    if (typeof page == 'undefined'){
        page = 0;
    }else {
        try {
            page = parseInt(page) - 1;
        }catch (error){
            page = 0;
        }
    }
    // 判断status
    if (typeof status != 'undefined'){
        try {
            status = parseInt(status);
        }catch (error){
            status = 0;
        }
    }
    // 实例化一个用户
    var User = Parse.Object.extend('User');
    var user = new User();
    user.id = userId;
    // 查询订单
    var query = new Parse.Query('OPOrder');
    query.equalTo('user', user);
    if (status){
        query.equalTo('status', status);
    }
    query.limit(limit);
    query.skip(page*limit);
    query.exists('store');
    query.descending('createdAt');
    query.include('orderProducts.product', 'expressCompany', 'store');
    query.find().then(function (results) {
        // 格式化返回的样式
        var response_content = [];
        results.forEach(function (item) {
            var temp = assert.obj2dic(item,['totalPrice', 'username', 'payPrice', 'status']);
            temp.orderProducts = [];
            temp.totalCount = 0;
            temp.store = item.get('store').get('name');
            temp.storeId = item.get('store').id;
            var expressCompany = item.get('expressCompany');
            if (typeof expressCompany != 'undefined'){
                temp['expressCom'] = expressCompany.get('code');
                temp['expressName'] = expressCompany.get('name');
                temp['expressNO'] = item.get('expressNumber');

            }
            var orderProducts = item.get('orderProducts');
            temp.hasReturn = false;
            orderProducts.forEach(function (orderProduct) {
                var temp_orderProduct = assert.obj2dic(orderProduct,['count', 'price']);
                temp_orderProduct.kdProductId = orderProduct.get('storeGood').id;
                delete temp_orderProduct.objectId;
                var product = orderProduct.get('product');
                temp_orderProduct.title = product.get('title');
                temp_orderProduct.images = product.get('images')[0];
                temp.orderProducts.push(temp_orderProduct);
                temp.totalCount += orderProduct.get('count');
                var orderReturnTag = orderProduct.get('orderReturn');
                var isReturn = typeof orderReturnTag != 'undefined';
                if (isReturn){
                    temp.hasReturn = true;
                }
            });
            response_content.push(temp);
        });
        res.json(assert.con2json(200, '获取订单成功', response_content));
    }, function (error) {
        res.json(assert.con2json(400, '获取订单失败' + error.message));
    });
};
// 获取单个kdOrder
exports.getkdOrder = function (req, res) {

    var orderId = req.params.id;
    var isShort = req.query.isShort;
    isShort = isShort == '1';
    if (!orderId){
        res.json(assert.con2json(400, '需要参数orderId'));
        return;
    }
    var query = new Parse.Query('OPOrder');
    query.include('orderProducts.product', 'expressCompany', 'orderProducts.orderReturn', 'store');
    query.get(orderId).then(function (result) {
        var orderProducts = result.get('orderProducts');
        var temp_order = {};
        // 格式化返回的字段
        if (isShort){
            temp_order['orderProducts'] = [];
            temp_order.store = result.get('store').get('name');
            temp_order.storeId = result.get('store').id;
            orderProducts.forEach(function (orderProduct) {
                var temp_orderProduct = assert.obj2dic(orderProduct,['price']);
                delete temp_orderProduct.objectId;
                temp_orderProduct.kdProductId = orderProduct.get('storeGood').id;
                // 判断order是否有申请退货
                var product = orderProduct.get('product');
                temp_orderProduct.images = product.get('images')[0];
                temp_orderProduct.title = product.get('title');
                temp_order['orderProducts'].push(temp_orderProduct);
            });
            res.json(assert.con2json(200, '获取订单成功', temp_order));
        }else {
            temp_order = assert.obj2dic(result,['expressPrice', 'username', 'payPrice', 'address', 'username','privilegePrice', 'mobile', 'totalPrice', 'status', 'createdAt', 'expressNumber', 'remark']);
            temp_order.store = result.get('store').get('name');
            temp_order.storeId = result.get('store').id;
            var remark = result.get('remark');
            if (typeof remark == 'undefined' || remark == ''){
                remark = '无备注';
            }
            temp_order.remark = remark;
            temp_order['createdAt'] = result.get('createdAt').Format('yyyy-MM-dd');
            temp_order['totalCount'] = 0;
            temp_order['expressNO'] = result.get('expressNumber');
            // 判断是否已经有快递信息
            if (typeof result.get('expressCompany') != 'undefined'){
                temp_order['expressCom'] = result.get('expressCompany').get('code');
                temp_order['expressName'] = result.get('expressCompany').get('name');
            }
            // 订单中商品的格式
            temp_order['orderProducts'] = [];
            temp_order['hasReturn'] = false;
            orderProducts.forEach(function (orderProduct) {
                var temp_orderProduct = assert.obj2dic(orderProduct,['count', 'price']);
                // delete temp_orderProduct.objectId;
                temp_orderProduct.kdProductId = orderProduct.get('storeGood').id;
                // 判断order是否有申请退货
                var orderReturnTag = orderProduct.get('orderReturn');
                var isReturn = typeof orderReturnTag != 'undefined';
                temp_orderProduct['orderReturn'] = isReturn;
                if (isReturn){
                    temp_orderProduct['orderReturnId'] = orderProduct.get('orderReturn').id;
                    temp_order.hasReturn = true;
                }
                var product = orderProduct.get('product');
                temp_orderProduct.images = product.get('images')[0];
                temp_orderProduct.title = product.get('title');
                temp_order.orderProducts.push(temp_orderProduct);
                temp_order.totalCount += orderProduct.get('count');
            });
            // 用时间戳做订单号
            temp_order['orderId'] = Date.parse(result['createdAt']);
            res.json(assert.con2json(200, '获取订单成功', temp_order));
        }
    }, function (error) {
        res.json(assert.con2json(400, '获取订单失败'));
    });
};
// 获取单个kdOrder状态
exports.getOrderStatus = function (req, res) {
    var orderId = req.query.orderId;
    if (!orderId){
        res.json(assert.con2json(101, '需要参数orderId'));
        return;
    }
    var query = new Parse.Query('OPOrder');
    query.select('status');
    query.get(orderId).then(function (order) {
        res.json(assert.con2json(200, '获取订单状态成功', order.get('status')));
    }, function (error) {
        res.json(assert.con2json(400,'获取订单状态失败'));
    });
};
// 删除购物车内的商品
function deleteShoppingItem(products, user) {
    var Product = Parse.Object.extend('OPProduct');
    var query = new Parse.Query('OPShoppingItem');
    var waitDel = [];
    for (var i=0; i<products.length; i++){
        var product = new Product();
        product.id = products[i]['product'];
        waitDel.push(product);
    }
    query.equalTo('user', user);
    query.containedIn('product', waitDel);
    query.find().then(function (result) {
        result.map(function (obj) {
            obj.destroy();
        });
    },function (error) {
        console.log(error);
    });
}
// 获取地址信息
function getAddress(addressId) {
    return new Promise(function (resolve, reject) {
        var query = new Parse.Query('OPAddress');
        query.get(addressId).then(function (address) {
            resolve(address);
        }, function (error) {
            reject(error)
        });
    });
}
// 获取店铺的信息
function getPharmacyInfo(memberId) {
    return new Promise(function (resolve, reject) {
        var User = Parse.Object.extend('User');
        var user = new User();
        user.id = memberId;
        var ownerQuery = new Parse.Query('PYPharmacy');
        ownerQuery.equalTo('owner', user);
        var memberQuery = new Parse.Query('PYPharmacy');
        memberQuery.containedIn('members', [user]);
        var mainQuery = Parse.Query.or(ownerQuery, memberQuery);
        mainQuery.first().then(function (pharmacy) {
            resolve(pharmacy);
        }, function (error) {
            reject(error);
        });
    });
}
// 获取订单商品的信息
function getOrderProductInfo(products) {
    return new Promise(function (resolve, reject) {
        var OrderProduct = Parse.Object.extend('OPOrderProduct');
        var productList = [];
        for (var i=0; i<products.length; i++){
            (function (i) {
                var query = new Parse.Query('OPProduct');
                productList[i] = query.get(products[i]['product']);
            })(i);
        }
        Promise.all(productList).then(function (pList) {
            var orderProducted = [];
            for(var j=0;j<pList.length;j++){
                var orderProduct = new OrderProduct();
                orderProduct.set('product', pList[j]);
                orderProduct.set('message', products[j]['goodRemark']);
                orderProduct.set('price', pList[j].get('salePrice'));
                orderProduct.set('count', parseInt(products[j]['count']));
                orderProducted[j] = orderProduct.save();
            }
            Promise.all(orderProducted).then(function (orderProductSaved) {
                resolve(orderProductSaved);
            },function (err,error) {
                console.log(err,error);
            })
        });
    });
}
//获取coupon
function getCoupon(couponId) {
    return new Promise(function (resolve, reject) {
        var queryCoupon = new Parse.Query('PYCoupon');
        queryCoupon.include('couponTemplate');
        queryCoupon.get(couponId).then(function (coupon) {
            resolve(coupon);
        }, function (error) {
            reject(error)
        });
    })
}
// 获取退单的数量
function getOrderReturnsCount(userId) {
    return new Promise(function (resolve, reject) {
        var user = new Parse.User();
        user.id = userId;
        var query = new Parse.Query('OPOrderReturn');
        query.equalTo('user', user);
        query.count().then(function (count) {
            resolve(count);
        }, function (error) {
            reject(error);
        });
    });
}
// 获取每种订单的数量
function getCategoryOrderCount(userId) {
    return new Promise(function (resolve, reject) {
        var user = new Parse.User();
        user.id = userId;
        var countList = [];
        for (var i=0;i<4;i++){
            (function (i) {
                var query = new Parse.Query('OPOrder');
                query.equalTo('user', user);
                query.equalTo('status', i);
                countList[i] = query.count()
            })(i);
        }
        Promise.all(countList).then(function (results) {
            resolve(results);
        }, function (error) {
            reject(error);
        })

    });
}
// 获取团购商品
function getGroupProductByGroupProductId(groupProductId) {
    return new Promise(function (resolve, reject) {
        var query = new Parse.Query('OPGroupProduct');
        query.get(groupProductId).then(function (result) {
            resolve(result.get('groupPrice'));
        }, function (error) {
            reject(error);
        });
    });
}